// 模拟App连接和通讯
package main

import (
	"acs/client"
	"acs/comet/config"
	"acs/comet/proto"
	"acs/pbmodel"
	"acs/taskprocess"
	"errors"
	"fmt"

	log "github.com/cihub/seelog"
	pb "github.com/golang/protobuf/proto"
	flags "github.com/jessevdk/go-flags"
)

func main() {
	var args struct {
		Concurrency uint16 `short:"n" default:"3" required:"yes" description:"模拟客户端数量"`
	}
	argParser := flags.NewNamedParser("app mock", flags.Default|flags.IgnoreUnknown)
	argParser.AddGroup("Mock parameters", "", &args)
	_, err := argParser.Parse()
	if err != nil {
		panic(err)
	}
	logger, err := log.LoggerFromConfigAsString(`<seelog>
    <outputs formatid="common">
        <console />
    </outputs>
    <formats>
    <format id="common" format="[%Level]%Date(2006/01/02 15:04:05.999)[%File:%Line] %Msg%n"/>
</formats>
</seelog>
	`)
	if err != nil {
		panic(err)
	}
	err = log.ReplaceLogger(logger)

	Config := config.InitConfig()

	hungCh := make(chan int, 1)


	uids := []string{"111", "112", "113", "114", "115", "116"}
	concurrent := int(args.Concurrency)
	log.Infof("Start tests with %v mockup clients.", concurrent)
	for ; concurrent > 0; concurrent-- {
		uid := uids[(concurrent-1)%len(uids)]
		c, err := client.NewClient(client.ClientConfig{
			Addr:           "127.0.0.1:8082",
			//Addr:           "123.59.226.60:8082",
			HeartBeatTtl:   24000,
			Logger:         logger,
			DataEncryptIV:  Config.DataEncryptIV,
			DataEncryptKey: Config.DataEncryptKey,
			HandshakeMessage: client.HandshakeMessage{
				Cmd: proto.CmdRegister,
				ReqMsg: &pbmodel.RegisterInfo{
					Appver:    pb.String("3.0.1"),
					BundleID:  pb.String("com.jumei.live.android"),
					System:    pb.Int32(int32(taskprocess.PlatformAndroid)),
					OSVersion: pb.String("9.3.1"),
					Brand:     pb.String("Huawei"),
					Model:     pb.String("MateS"),
					UID:       pb.String(fmt.Sprintf("%v", uid)),
					UUID:      pb.String("X-xx"),
					LPID:      pb.String("patch-3.0.2-001"),
					LSID:      pb.String("3.0.1-211"),
				},
				Resp: &pbmodel.RegisterInfoResp{},
			},
		})
		if err != nil {
			log.Warnf("%v", err)
			continue
		}
		eventCmdData := new(TestEventMessage)
		eventCmdRespData := new(pbmodel.EventResp)
		c.RegisterRequestHandler(eventHandler, proto.CmdEvent, eventCmdData, eventCmdRespData)

	}
	<-hungCh
}

type TestEventMessage struct {
	pbmodel.Event
}

func (_ *TestEventMessage) New() pb.Message {
	return new(pbmodel.Event)
}
func eventHandler(eventInfoI pb.Message) (resp pb.Message, err error) {
	eventInfo, ok := eventInfoI.(*pbmodel.Event)
	if !ok {
		err = errors.New("type error: event message should be *pbmodel.event")
	}
	fmt.Println("====================", *eventInfo.Content) //打印内容
	log.Debugf("Got ACS message: %+v", *eventInfo)
	eventResp := new(pbmodel.EventResp)
	var status int32 = 6000
	eventResp.Status = &status
	resp = eventResp
	return
}
